package com.manuserve.mountainduck;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;


import com.manuserve.mountainduck.kernel.GameBoard;
import com.manuserve.mountainduck.playgame.BaseGameActivity;
import com.google.android.gms.ads.*;
import android.os.Handler;

import android.view.View;
import android.view.View.OnClickListener;


public class MainActivity extends BaseGameActivity {

	private Handler frame = new Handler();
    private AdView adView;

    public InterstitialAd interstitial;

    private int score ;

    boolean  isLaunchedActivityScore = true; //Pour éviter que le 1er log transparent aboutisse à une redirection vers le game center

    boolean  isConcreteLaunchedActivityScore = false;

    boolean isLaunchedShare = true ;

    private static final String AD_UNIT_ID = "ca-app-pub-3623918836613471/9558997748";

    //Divide the frame by 1000 to calculate how many times per second the screen will update.
    private static final int FRAME_RATE = 20; //20ms -> 50 frames per second
    @Override
    public void onCreate(Bundle savedInstanceState) {



        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        super.onCreate(savedInstanceState);


        this.interstitial = new InterstitialAd(this);
        this.interstitial.setAdUnitId("ca-app-pub-3623918836613471/3416562540");


        // Create an ad request. Check logcat output for the hashed device ID to
        // get test ads on a physical device.
       //AdRequest adRequest = new AdRequest.Builder()
        //          .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        //    .addTestDevice("2E35D0A46DC08F525FA5F140AB428D54")
        //    .build();

        // Start loading the ad in the background.
        // adView.loadAd(adRequest);
        //interstitial.loadAd(adRequest);



        //We can't initialize the graphics immediately because the layout manager
        //needs to run first, thus we call back in a sec.
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            @Override
            public void run() {
                initGfx();
            }
        }, 1000);
    }


    public void handleShare(String message) {
        if(isLaunchedShare) return ;
        isLaunchedShare = true ;
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("text/plain");
        share.putExtra(Intent.EXTRA_TEXT, message);
        startActivity(Intent.createChooser(share, "Share your climb"));
    }



    //Method for getting touch state--requires android 2.1 or greater
    @Override
    synchronized public boolean onTouchEvent(MotionEvent ev) {

        final int action = ev.getAction();
        switch (action & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:

                ((GameBoard)findViewById(R.id.the_canvas)).handleActionDown(ev.getX(),ev.getY());

                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                break;
        }
        return true;
    }

    synchronized public void initGfx() {
        //It's a good idea to remove any existing callbacks to keep
        //them from inadvertently stacking up.
        isLaunchedShare = false ;
        frame.removeCallbacks(frameUpdate);

        if(!((GameBoard)findViewById(R.id.the_canvas)).isReady())
            ((GameBoard)findViewById(R.id.the_canvas)).init(this);
        frame.postDelayed(frameUpdate, 50);
    }


    @Override
    public void onSignInFailed() {

    }

    @Override
    public void onSignInSucceeded() {
        if( ! isLaunchedActivityScore ) {
            redirectionGameCenter();
        }
    }

    public void redirectionGameCenter() {
        isLaunchedActivityScore = true ;
        isConcreteLaunchedActivityScore = true ;
        getGamesClient().submitScore( "CgkIrNX-joIJEAIQAg", score );
        startActivityForResult(getGamesClient().getLeaderboardIntent("CgkIrNX-joIJEAIQAg"), 1);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(isConcreteLaunchedActivityScore)
            this.finish();
    }




    @Override
    protected void onPause() {
        super.onPause();

        //AdRequest adRequest = new AdRequest.Builder()
        //       .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        //       .addTestDevice("2E35D0A46DC08F525FA5F140AB428D54")
        //       .build();
        //interstitial.loadAd(adRequest);
        ((GameBoard)findViewById(R.id.the_canvas)).pause();    }
    protected void onResume() {
        super.onResume();
       // if (interstitial.isLoaded()) {
       //     interstitial.show();
       // }
        ((GameBoard)findViewById(R.id.the_canvas)).resume();

        //if (adView != null) {
        //    adView.resume();
       // }

    }

    /** Called before the activity is destroyed. */
    @Override
    public void onDestroy() {
         //Destroy the AdView.
        //if (adView != null) {
        //     adView.destroy();
         //}
        super.onDestroy();
    }

    public void handleScore(int score) {
        isLaunchedActivityScore = false ;
        this.score = score ;
        if(isSignedIn())
            redirectionGameCenter();
        else
            beginUserInitiatedSignIn();
    }


    private Runnable frameUpdate = new Runnable() {
      @Override
      synchronized public void run() {
              frame.removeCallbacks(frameUpdate);
              //make any updates to on screen objects here
              //then invoke the on draw by invalidating the canvas
          if(((GameBoard)findViewById(R.id.the_canvas)).isReady()) {
              ((GameBoard)findViewById(R.id.the_canvas)).update();
              (findViewById(R.id.the_canvas)).invalidate();

          }
          frame.postDelayed(frameUpdate, FRAME_RATE);

      }


 };
    
}
